<?php

/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */

class Application_Model_ReviewMapper extends Ahs_Model_Mapper
{

    public function __construct(array $options = null)
    {
        parent::__construct($options);
        $this->DbTableName = 'Application_Model_DbTable_Reviews';
        $this->PropertiesMap = array
        (
            "Id"            => "review_id",
            "AuthorId"      => "review_author_id",
            "BookId"        => "review_book_id",
            "Subject"       => "review_subject",
            "Text"          => "review_text",
            "CreationDate"  => "review_creationdate",
            "ModifiedDate"  => "review_modifieddate",
            "DeletedDate"   => "review_deleteddate",
        );
    }
    
    /**
     * Get all reviews
     * @return Array(Application_Model_Review)
     */
    public function fetchAll()
    {        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(''.$this->getColumn('DeletedDate').' IS NULL');
        $rows = $table->fetchAll($select);
        return $this->_toReviews($rows);
    }
    
    /**
     * Get a review by its ID
     * 
     * @param integer $id
     * @return Application_Model_Review
     */
    public function fetchById($id)
    {
        $row = $this->getDbTable()->fetchRow(array(''.$this->getColumn('Id').' = ?' => $id));
        return $this->_toReview($row);
    }
    
    /**
     * Get all reviews for an author
     * 
     * @param integer $author_id
     * @param integer $page_nr      If you wish to use paging, pass the page-number. To disable paging, 
     *                              pass null as value (default) and return all rows.
     * @param integer $nr_results   The number of results per page, defaults to 10.
     * @return Array(Application_Model_Review)
     */
    public function fetchByAuthorId($author_id, $page_nr=null, $nr_results=10)
    {
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->where(
                    ''.$this->getColumn('AuthorId').' = :id'
                       . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->order(''.$this->getColumn('CreationDate').' DESC');
        
        if($page_nr != null && $page_nr > 0)
            $select->limitPage($page_nr, $nr_results);
        
        $rows = $table->fetchAll($select);
        return $this->_toReviews($rows);
    }
    
    /**
     * Search review by book
     * 
     * @param integer $book_id
     * @param integer $page_nr      If you wish to use paging, pass the page-number. To disable paging, 
     *                              pass null as value (default) and return all rows.
     * @param integer $nr_results   The number of results per page, defaults to 10.
     * @return Array(Application_Model_Review) 
     */
    public function fetchByBookId($book_id, $page_nr=null, $nr_results=10)
    {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(
                    ''.$this->getColumn('BookId').' = :book_id'
                        . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                )
               ->bind(array(':book_id' => $book_id))
               ->order(''.$this->getColumn('CreationDate').' DESC');
        
        if($page_nr != null && $page_nr > 0)
            $select->limitPage($page_nr, $nr_results);
        
        $rows = $table->fetchAll($select);
        return $this->_toReviews($rows);
    }
    
    /**
     * Get the total number of reviews
     * 
     * @return integer
     */
    public function getCount()
    {
        $ids    = array();
        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table, array('count(*) as count'));
        $select->where(''.$this->getColumn('DeletedDate').' IS NULL');
        
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;
    }
    
    /**
     * Get the total number of reviews for a book
     * 
     * @param integer $book_id
     * @return integer
     */
    public function getCountByBookId($book_id)
    {
        $ids    = array();
        
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->from($table, array('count(*) as count'));
        $select->where(
                    ''.$this->getColumn('BookId').' = :book_id'
                        . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                )
               ->bind(array(':book_id' => $book_id));
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;
    }
    
    /**
     * Save a review
     *
     * @param Application_Model_Review $review
     */
    public function save(Application_Model_Review $review)
    {    
        $review_id = $review->Id;
        
        $data = $this->_getTableValues($review, array("Id"));
        $data[$this->getColumn("ModifiedDate")] = new Zend_Db_Expr('NOW()');
        
        if(null == $review_id)
        {
            // Set some default values
            $data[$this->getColumn("CreationDate")] = new Zend_Db_Expr('NOW()');
            $data[$this->getColumn("AuthorId")]     = $this->getLoggedInUserId();
            
            // Insert and get the id
            $review_id    = $this->getDbTable()->insert($data);
        }
        else
        {
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $review_id));
        }
        
        return $review_id;
    }
    
    /**
     * Delete a review by id
     *
     * @param integer $id
     */
    public function delete($id)
    {   
        if (null != $id)
        {
            $data[$this->getColumn('DeletedDate')] = new Zend_Db_Expr('NOW()');
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $id));
        }
    }
    
    /**
     * Undelete a review by id
     *
     * @param integer $id
     */
    public function undelete($id)
    {   
        if (null != $id)
        {
            $data[$this->getColumn('DeletedDate')] = new Zend_Db_Expr('NULL');
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $id));
        } 
    }
    
    /**
     * Convert a row to object
     * 
     * @param Zend_Db_Table_Row_Abstract $row
     * @return Application_Model_Review
     */
    private function _toReview(Zend_Db_Table_Row_Abstract $row = null)
    {
        // Create our object
        $object = new Application_Model_Review();
        
        // Only go on if we actually have a row
        if($row)
        {
            // We have a propertiesmap, let's try to map it back to an object
            foreach($this->PropertiesMap as $key=>$column)
            {
                if(isset($row[$column]))
                    $object->$key      = $row[$column];
            }
        }

        return $object;
    }

    /**
     * Convert a rowset to an array of objects
     * 
     * @param Zend_Db_Table_Rowset_Abstract $rows
     * @return Array(Application_Model_Review)
     */
    private function _toReviews(Zend_Db_Table_Rowset_Abstract $rows = null)
    {
        $results = array();
        if ($rows)
        {
            foreach ($rows as $row)
            {
                $results[] = $this->_toReview($row);
            }
        }
        return $results;
    }
}